<template>
    <view class="add-form-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header :title="isEdit ? '编辑生长记录' : '新增生长记录'"></page-header>
        <!-- 使用地块选择器组件 -->
        <LandSelector
            ref="landSelector"
            @selection-change="handleLandSelectionChange"></LandSelector>

        <!-- 使用条田选择器组件 -->
        <SectionSelector
            ref="sectionSelector"
            @areaChange="handleAreaChange"
            @usersChange="handleUsersChange"
            @seedChange="handleSeedChange"></SectionSelector>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form">
                <uni-forms-item label="记录时间" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="formData.dateRange"
                        :border="false"
                        :label-width="200"
                        @change="dateRangeChange">
                        <view class="uni-date-picker-container">
                            <text
                                :class="{
                                    placeholder: !formData.dateRangeText,
                                }">
                                {{ formData.dateRangeText || '请选择记录时间' }}
                            </text>
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item label="作物信息" name="cropName" :label-width="200" required>
                    <uni-easyinput
                        v-model="formData.cropName"
                        placeholder="请输入作物信息"
                        disabled></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="面积" name="area">
                    <uni-easyinput
                        type="digit"
                        v-model="formData.area"
                        placeholder="请输入面积"
                        disabled>
                        <template #right>
                            <text class="input-unit">亩</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="basic-info">
            <view class="section-title">生长数据</view>

            <uni-forms
                ref="growthForm"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form">
                <uni-forms-item label="生长阶段" name="growthStageId" :label-width="200" required>
                    <uni-data-select
                        v-model="formData.growthStageId"
                        :localdata="growthStagesData"
                        placeholder="请选择生长阶段"
                        @change="handleGrowthStageChange"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item
                    label="阶段"
                    name="growthStageSubclassId"
                    :label-width="200"
                    required>
                    <uni-data-select
                        v-model="formData.growthStageSubclassId"
                        :localdata="subGrowthStagesData"
                        placeholder="请选择子生长阶段"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="叶面积" name="leafArea" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.leafArea"
                        placeholder="请输入叶面积">
                        <template #right>
                            <text class="input-unit">cm²</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="株高" name="plantHeight" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.plantHeight"
                        placeholder="请输入株高">
                        <template #right>
                            <text class="input-unit">cm</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="叶龄" name="leafAge" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.leafAge"
                        placeholder="请输入叶龄"></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="personInCharge">
                    <uni-easyinput
                        v-model="formData.personInCharge"
                        placeholder="请输入负责人姓名"
                        disabled></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="备注" name="remark">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.remark"
                        placeholder="请输入备注信息"
                        :maxlength="200"></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>

            <image-uploader ref="imageUploader" :images="formData.images" :maxCount="9" />
        </view>
        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">点击上传</view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import LandSelector from '@/components/LandSelector/index.vue'
import SectionSelector from '@/components/SectionSelector/index.vue'
import ImageUploader from '@/components/ImageUploader/index.vue'
import { growth } from '@/utils/api/index.js'
import { formatDate, getDefaultDateRange } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        LandSelector,
        SectionSelector,
        ImageUploader,
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
            userInfo: 'getUserInfo',
        }),
    },
    data() {
        const defaultDateRange = getDefaultDateRange()
        return {
            isEdit: false,
            editId: null,
            formData: {
                cropId: '',
                cropName: '',
                cropType: '',
                dateRange: defaultDateRange.dateRange,
                dateRangeText: defaultDateRange.dateRangeText,
                growthStageId: '',
                growthStage: '',
                growthStageSubclassId: '',
                growthStageSubclass: '',
                leafArea: '',
                plantHeight: '',
                leafAge: '',
                images: [],
                plotId: '',
                fieldId: '',
                remark: '',
                personInCharge: '',
                personInId: '',
                area: '',
            },
            rules: {
                dateRange: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择记录时间',
                        },
                    ],
                },
                cropName: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入作物信息',
                        },
                    ],
                },
                growthStageId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择生长阶段',
                        },
                    ],
                },
                growthStageSubclassId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择子生长阶段',
                        },
                    ],
                },
                leafArea: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入叶面积',
                        },
                    ],
                },
                plantHeight: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入株高',
                        },
                    ],
                },
                leafAge: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入叶龄',
                        },
                    ],
                },
            },
            growthStagesData: [], // 生长阶段字典数据
            subGrowthStagesData: [], // 子生长阶段字典数据
            selectedLands: [], // 选中的地块
            selectedSections: [], // 选中的条田
        }
    },
    onLoad(options) {
        // 加载字典数据
        this.loadDictData()

        if (options.id) {
            this.isEdit = true
            this.editId = options.id
            this.fetchRecordDetail(options.id)
        } else {
            // 设置默认的负责人和负责人ID
            console.log('用户信息', this.userInfo)
            this.formData.personInId = this.userInfo.id
            this.formData.personInCharge = this.userInfo.nickname
        }
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                // 加载生长阶段字典
                await this.getDictByType('generation_phase')
                this.growthStagesData = this.formatDictToSelectData('generation_phase')
            } catch (error) {
                console.error('加载字典数据失败:', error)
            }
        },

        // 将字典数据格式化为下拉选择框所需的格式
        formatDictToSelectData(dictType) {
            const dictList = this.getDictByType(dictType)
            return dictList.map((item) => ({
                value: item.value,
                text: item.label,
            }))
        },

        // 处理日期变化
        dateChange(e) {
            this.formData.startDate = e
        },

        // 处理日期范围变化
        dateRangeChange(e) {
            this.formData.dateRange = e
            this.formData.dateRangeText = e.map((item) => item).join(' - ')
        },

        // 处理地块选择变化
        handleLandSelectionChange() {
            this.updateSelectedLands()
        },

        // 处理条田选择变化
        handleAreaChange(area) {
            this.formData.area = area
        },

        handleUsersChange(users) {
            this.formData.personInId = users.map((item) => item.userId).join(',')
            this.formData.personInCharge = users.map((item) => item.userName).join(',')
        },
        handleSeedChange(seed) {
            console.log('作物变化handleSeedChange', seed)
            this.formData.cropId = seed.map((item) => item.seedId).join(',')
            this.formData.cropName = seed.map((item) => item.seedName).join(',')
            this.formData.cropType = seed.map((item) => item.cropType).join(',')
        },

        // 处理生长阶段变化
        async handleGrowthStageChange() {
            // 根据选择的生长阶段，更新子生长阶段下拉选项
            if (this.formData.growthStageId) {
                try {
                    // 根据选中的生长阶段获取对应的子生长阶段字典
                    const growthStageValue = this.formData.growthStageId

                    // 从字典中获取对应的子生长阶段值
                    const growthStageDict = this.getDictByType('generation_phase')
                    const selectedStage = growthStageDict.find(
                        (item) => item.value === growthStageValue
                    )

                    if (selectedStage) {
                        // 加载对应的子生长阶段字典
                        await this.getDictByType(selectedStage.value)
                        this.subGrowthStagesData = this.formatDictToSelectData(selectedStage.value)
                    } else {
                        this.subGrowthStagesData = []
                    }
                } catch (error) {
                    console.error('获取子生长阶段字典失败:', error)
                    this.subGrowthStagesData = []
                }
            } else {
                this.subGrowthStagesData = []
            }

            // 重置子生长阶段
            if (
                this.formData.growthStageSubclassId &&
                !this.subGrowthStagesData.some(
                    (item) => item.value === this.formData.growthStageSubclassId
                )
            ) {
                this.formData.growthStageSubclassId = ''
                this.formData.growthStageSubclass = ''
            }
        },

        // 更新选中的地块数据
        updateSelectedLands() {
            if (this.$refs.landSelector) {
                this.selectedLands = this.$refs.landSelector.getSelectedLands()
                console.log('更新选中的地块:', this.selectedLands)

                // 当地块选择变化时，更新条田选择器
                if (this.$refs.sectionSelector) {
                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands)
                    // 更新选中的条田
                    this.updateSelectedSections()
                }
            }
        },

        // 更新选中的条田数据
        updateSelectedSections() {
            if (this.$refs.sectionSelector) {
                this.selectedSections = this.$refs.sectionSelector.getSelectedSections()
                console.log('更新选中的条田:', this.selectedSections)
            }
        },

        // 验证表单
        validateForm() {
            // 更新选中的地块和条田
            this.updateSelectedLands()
            this.updateSelectedSections()

            // 检查是否选择了地块
            if (!this.$refs.landSelector.validate()) {
                uni.showToast({
                    title: '请选择至少一个地块',
                    icon: 'none',
                })
                return false
            }

            // 检查是否选择了条田
            if (!this.$refs.sectionSelector.validate()) {
                uni.showToast({
                    title: '请选择至少一个条田',
                    icon: 'none',
                })
                return false
            }

            return true
        },

        // 获取记录详情
        async fetchRecordDetail(id) {
            try {
                uni.showLoading({ title: '加载中...' })
                const res = await growth.getGrowthRecordDetail(id)
                if (res.code === 0 && res.data) {
                    const recordData = res.data
                    // 设置日期范围
                    const dateRange = [recordData.startDate, recordData.endDate]
                    const dateRangeText = dateRange.join(' - ')

                    this.formData = {
                        ...this.formData,
                        ...recordData,
                        dateRange,
                        dateRangeText,
                        growthStageId: recordData.growthStageId,
                        growthStage: recordData.growthStage,
                        growthStageSubclassId: recordData.growthStageSubclassId,
                        growthStageSubclass: recordData.growthStageSubclass,
                        images: recordData.images ? recordData.images.split(',') : [],
                    }
                    // 字典
                    this.handleGrowthStageChange()
                    // 等待组件加载完成后，设置地块选择状态
                    this.$nextTick(() => {
                        // 确保组件已完全加载
                        setTimeout(() => {
                            // 设置地块选择器中选中的地块
                            if (this.$refs.landSelector && this.formData.plotId) {
                                this.$refs.landSelector.setSelectedLands(this.formData.plotId)
                                this.updateSelectedLands()

                                // 更新条田选择器的地块ID
                                if (this.$refs.sectionSelector) {
                                    this.$refs.sectionSelector.setSelectedParcels(
                                        this.selectedLands
                                    )

                                    // 设置条田选择状态
                                    if (this.formData.fieldId) {
                                        this.$refs.sectionSelector.setSelectedFields(
                                            this.formData.fieldId
                                        )
                                        this.updateSelectedSections()
                                    }
                                }
                            }
                        }, 1200)
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '获取记录详情失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('获取记录详情失败:', error)
                uni.showToast({
                    title: '获取记录详情失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 提交表单
        submitForm() {
            this.$refs.form.validate().then((formValid) => {
                if (!formValid) return

                this.$refs.growthForm.validate().then(async (growthFormValid) => {
                    if (!growthFormValid) return

                    // 使用validateForm方法验证地块和条田选择
                    if (!this.validateForm()) {
                        return
                    }

                    try {
                        // 验证 cropId 不能包含逗号
                        if (this.formData.cropId && this.formData.cropId.includes(',')) {
                            uni.showToast({
                                title: '不能选择多个作物',
                                icon: 'none',
                            })
                            return
                        }
                        // cropType
                        if (this.formData.cropType && this.formData.cropType.includes(',')) {
                            uni.showToast({
                                title: '不能选择多个作物',
                                icon: 'none',
                            })
                            return
                        }

                        uni.showLoading({ title: '提交中...' })

                        // 获取选中的地块和条田
                        this.updateSelectedLands()
                        this.updateSelectedSections()

                        let plotId = this.selectedLands.map((item) => item.id)
                        let fieldId = this.selectedSections.map((item) => item.id)

                        let plotName = this.selectedLands.map((item) => item.name)
                        let fieldName = this.selectedSections.map((item) => item.name)

                        // 获取图片列表
                        const imageList = this.$refs.imageUploader.getImageList()
                        // this.formData.cropId

                        // 获取生长阶段和子生长阶段的名称
                        const growthStageDict = this.getDictByType('generation_phase')
                        const selectedStage = growthStageDict.find(
                            (item) => item.value === this.formData.growthStageId
                        )
                        const growthStageName = selectedStage ? selectedStage.label : ''

                        let growthStageSubclassName = ''
                        if (this.formData.growthStageSubclassId && selectedStage) {
                            const subStageDict = this.getDictByType(selectedStage.value)
                            const selectedSubStage = subStageDict.find(
                                (item) => item.value === this.formData.growthStageSubclassId
                            )
                            growthStageSubclassName = selectedSubStage ? selectedSubStage.label : ''
                        }

                        // 准备提交的数据
                        const submitData = {
                            id: this.isEdit ? this.editId : undefined,
                            startDate: this.formData.dateRange[0],
                            endDate: this.formData.dateRange[1],
                            cropId: this.formData.cropId,
                            cropName: this.formData.cropName,
                            cropType: this.formData.cropType,
                            plotId: plotId?.join(','), // 地块ID
                            fieldId: fieldId?.join(','), // 条田ID
                            plotName: plotName?.join(','), // 地块名称
                            fieldName: fieldName?.join(','), // 条田名称
                            growthStageId: this.formData.growthStageId,
                            growthStage: growthStageName,
                            growthStageSubclassId: this.formData.growthStageSubclassId,
                            growthStageSubclass: growthStageSubclassName,
                            leafArea: parseFloat(this.formData.leafArea),
                            plantHeight: parseFloat(this.formData.plantHeight),
                            leafAge: parseFloat(this.formData.leafAge),
                            personInCharge: this.formData.personInCharge,
                            personInId: this.formData.personInId,
                            area: parseFloat(this.formData.area || 0),
                            images: imageList.join(','),
                            remark: this.formData.remark || '',
                        }

                        // 调用API提交数据
                        const apiMethod = this.isEdit
                            ? growth.updateGrowthRecord
                            : growth.createGrowthRecord

                        const res = await apiMethod(submitData)

                        if (res.code === 0) {
                            uni.showToast({
                                title: this.isEdit ? '更新成功' : '添加成功',
                                icon: 'success',
                            })

                            // 返回上一页
                            setTimeout(() => {
                                uni.navigateBack()
                            }, 1500)
                        } else {
                            uni.showToast({
                                title: res.msg || (this.isEdit ? '更新失败' : '添加失败'),
                                icon: 'none',
                            })
                        }
                    } catch (error) {
                        console.error(this.isEdit ? '更新记录失败:' : '添加记录失败:', error)
                        uni.showToast({
                            title: this.isEdit ? '更新失败' : '添加失败',
                            icon: 'none',
                        })
                    } finally {
                        uni.hideLoading()
                    }
                })
            })
        },
    },
}
</script>

<style lang="scss">
// 样式已在common.scss中定义
</style>
